import { Task } from '../database/init'

// 函数调用结果接口
export interface FunctionCallResult {
  success: boolean
  data?: any
  error?: string
  message?: string
}

// 函数执行器接口
export interface FunctionExecutor {
  name: string
  description: string
  parameters: any
  execute: (args: any, context: any) => Promise<FunctionCallResult>
}

// 上下文接口
export interface AIContext {
  userId: string
  currentTasks: Task[]
  userPreferences?: any
  sessionId?: string
}

// 函数注册表
class AIFunctionRegistry {
  private functions: Map<string, FunctionExecutor> = new Map()

  // 注册函数
  register(func: FunctionExecutor): void {
    this.functions.set(func.name, func)
  }

  // 获取所有函数定义（用于OpenAI）
  getFunctionDefinitions(): any[] {
    return Array.from(this.functions.values()).map(func => ({
      name: func.name,
      description: func.description,
      parameters: func.parameters
    }))
  }

  // 获取工具定义（用于OpenAI v5.17.0版本）
  getToolDefinitions(userId?: string): any[] {
    return Array.from(this.functions.values()).map(func => ({
      type: 'function',
      function: {
        name: func.name,
        description: func.description,
        parameters: func.parameters
      }
    }))
  }

  // 执行函数调用
  async executeFunction(name: string, args: any, context: AIContext): Promise<FunctionCallResult> {
    const func = this.functions.get(name)
    if (!func) {
      return {
        success: false,
        error: `Function ${name} not found`
      }
    }

    try {
      return await func.execute(args, context)
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  // 获取函数列表
  getFunctionNames(): string[] {
    return Array.from(this.functions.keys())
  }
}

// 创建全局注册表实例
export const aiFunctionRegistry = new AIFunctionRegistry()

// 任务相关函数
export const taskFunctions = {
  // 创建任务
  createTask: {
    name: "create_task",
    description: "创建新任务",
    parameters: {
      type: "object",
      properties: {
        title: { 
          type: "string", 
          description: "任务标题" 
        },
        description: { 
          type: "string", 
          description: "任务描述" 
        },
        priority: { 
          type: "string", 
          enum: ["P0", "P1", "P2", "P3"],
          description: "任务优先级"
        },
        dueDate: { 
          type: "string", 
          format: "date-time",
          description: "截止日期"
        },
        category: { 
          type: "string", 
          description: "任务分类" 
        },
        tags: {
          type: "array",
          items: { type: "string" },
          description: "任务标签"
        }
      },
      required: ["title"]
    }
  },

  // 更新任务
  updateTask: {
    name: "update_task",
    description: "更新现有任务",
    parameters: {
      type: "object",
      properties: {
        taskId: { 
          type: "string", 
          description: "任务ID" 
        },
        updates: { 
          type: "object", 
          description: "要更新的字段",
          properties: {
            title: { type: "string" },
            description: { type: "string" },
            priority: { type: "string", enum: ["P0", "P1", "P2", "P3"] },
            status: { type: "string", enum: ["todo", "in_progress", "review", "done"] },
            dueDate: { type: "string", format: "date-time" },
            category: { type: "string" },
            tags: { type: "array", items: { type: "string" } }
          }
        }
      },
      required: ["taskId", "updates"]
    }
  },

  // 查询任务
  queryTasks: {
    name: "query_tasks",
    description: "查询任务列表",
    parameters: {
      type: "object",
      properties: {
        filters: {
          type: "object",
          properties: {
            status: { type: "string", enum: ["todo", "in_progress", "review", "done"] },
            priority: { type: "string", enum: ["P0", "P1", "P2", "P3"] },
            category: { type: "string" },
            tags: { type: "array", items: { type: "string" } },
            dueDate: { type: "string", description: "截止日期范围" }
          }
        },
        sortBy: { 
          type: "string", 
          enum: ["created_at", "due_date", "priority", "title"],
          description: "排序方式"
        },
        limit: { 
          type: "number", 
          description: "返回数量限制",
          default: 10
        }
      }
    }
  },

  // 完成任务
  completeTask: {
    name: "complete_task",
    description: "标记任务为完成",
    parameters: {
      type: "object",
      properties: {
        taskId: { 
          type: "string", 
          description: "任务ID" 
        },
        notes: { 
          type: "string", 
          description: "完成备注" 
        }
      },
      required: ["taskId"]
    }
  },

  // 删除任务
  deleteTask: {
    name: "delete_task",
    description: "删除任务",
    parameters: {
      type: "object",
      properties: {
        taskId: { 
          type: "string", 
          description: "任务ID" 
        }
      },
      required: ["taskId"]
    }
  },

  // 获取任务统计
  getTaskStats: {
    name: "get_task_stats",
    description: "获取任务统计信息",
    parameters: {
      type: "object",
      properties: {
        period: { 
          type: "string", 
          enum: ["today", "week", "month", "all"],
          description: "统计周期",
          default: "week"
        }
      }
    }
  }
}

export default aiFunctionRegistry
